//
//  GGPicBrowsePage.m
//  test
//
//  Created by kepuG on 17/2/28.
//  Copyright © 2017年 test. All rights reserved.
//

#import "GGPicBrowsePage.h"

@interface GGPicBrowsePage ()


@property (strong ,nonatomic) UIViewController *parentVC;

/**push 之前的window的截图*/
@property (nonatomic,strong) UIImage* screenshot;
@property (strong ,nonatomic) UIImageView *screenBackView;
/**点击的小图的初始位置*/
@property (assign ,nonatomic) CGRect smallRect;
/**点击截取到的视图*/
@property (strong ,nonatomic) UIView *smallView;


/**
 *  布局属性
 */



@end

@implementation GGPicBrowsePage


-(instancetype)initWithParentVC:(UIViewController*)parentVC contentView:(UIView*)contentVeiw{
    self = [super init];
    if (self) {
        
        self.parentVC = parentVC;
        self.screenshot = [self _screenshotFromView:[UIApplication sharedApplication].keyWindow];
        self.smallRect = contentVeiw.frame;
        
        UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
        self.screenBackView.image = self.screenshot;
        [self.view addSubview:self.screenBackView];
        [self.view addSubview:contentVeiw];
        self.smallView = contentVeiw;
        
        CGRect originRect = [contentVeiw convertRect:contentVeiw.frame toView:imageview];
        DebugLog(@"==origin=%@",NSStringFromCGRect(originRect));
    }
    return self;
}


-(UIImageView *)screenBackView{

    if (_screenBackView == nil) {
        _screenBackView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height)];
    }
    return _screenBackView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

-(void)show{
    
    __weak typeof(self) weakSelf = self;
    CGFloat x = 10;
    CGFloat y = 130;
    
    CGFloat width = kScreen_Width - 10*2;
    CGFloat height = width;
    
    [self.parentVC presentViewController:self animated:NO completion:^{
        [UIView animateWithDuration:0.4 animations:^{
            
            weakSelf.smallView.frame = CGRectMake(x, y, width, height);
            weakSelf.screenBackView.alpha = 0;
        }];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [super touchesBegan:touches withEvent:event];
    
    self.screenBackView.alpha = 1;
    
    [UIView animateWithDuration:0.6 animations:^{
        self.smallView.frame = self.smallRect;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

#pragma mark -懒加载
- (UIImage *)_screenshotFromView:(UIView *)aView {
    
    UIGraphicsBeginImageContextWithOptions(aView.bounds.size,NO,[UIScreen mainScreen].scale);
    [aView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage* screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenshotImage;
}

@end
